package landlords.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import landlords.channel.ChannelUtils;
import landlords.entity.ClientSide;
import landlords.entity.ServerTransferData;
import landlords.enums.ClientEventCode;
import landlords.enums.ClientRole;
import landlords.enums.ClientStatus;
import landlords.enums.ServerEventCode;
import landlords.print.SimplePrinter;
import landlords.server.ServerContains;
import landlords.server.event.ServerEventListener;

public class ProtobufTransferHandler extends ChannelInboundHandlerAdapter {

    public void channelRegistered(ChannelHandlerContext ctx){
        Channel ch=ctx.channel();
        //初始化客户信息
        ClientSide clientSide=new ClientSide(getId(ctx.channel()), ClientStatus.TO_CHOOSE,ch);
        //设置用户昵称
        clientSide.setNickname(String .valueOf(clientSide.getId()));
        //默认设置角色为玩家
        clientSide.setRole(ClientRole.PLAYER);
        ServerContains.CLIENT_SIDE_MAP.put(clientSide.getId(), clientSide);
        SimplePrinter.serverLog("有客户端连接到服务器："+clientSide.getId());

        //向客户端发送消息：连接成功
        ChannelUtils.pushToClient(ch, ClientEventCode.CODE_CLIENT_CONNECT,String.valueOf(clientSide.getId()));
        //向客户端发送消息：设置昵称
        ChannelUtils.pushToClient(ch,ClientEventCode.CODE_CLIENT_NICKNAME_SET,null);


        System.out.println();
    }

    public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception{
        if(msg instanceof ServerTransferData){
            ServerTransferData.ServerTransferDataProtoc serverTransferData=(ServerTransferData.ServerTransferDataProtoc) msg;
            ServerEventCode code=ServerEventCode.valueOf(serverTransferData.getCode());
            //获取客户端信息
            ClientSide client=ServerContains.CLIENT_SIDE_MAP.get(getId(ctx.channel()));
            SimplePrinter.serverLog(client.getId()+" | "+client.getNickname()+" do:"+code.getMsg());
            ServerEventListener.get(code).call(client,serverTransferData.getData());

        }
    }

    private int getId(Channel channel){
        String longId=channel.id().asLongText();
        Integer clientId= ServerContains.CHANNEL_ID_MAP.get(longId);
        if(clientId==null){
            clientId=ServerContains.getClientId();
            ServerContains.CHANNEL_ID_MAP.put(longId,clientId);
        }
        return clientId;
    }
}
